package net.ecpt.crm.services;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import javolution.util.FastList;
import javolution.util.FastMap;

public class CrmUserLoginServices {
	 public static String module = CrmUserLoginServices.class.getName();
    /**
     * 禁用bu，同时禁用该bu所有人员
     */
    public static Map<String, Object> disableBuAndUserLogin(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();

	List toBeStore = new ArrayList();
//	    GenericValue userLogin = (GenericValue)context.get("userLogin");
	// String ownerUserId=userLogin.getString("userLoginId");
	// Timestamp now =UtilDateTime.nowTimestamp();
	try {
	    String enabled = (String) context.get("enabled");
	    String partyIdFrom = (String) context.get("partyIdFrom");
	    String isArea = (String) context.get("isArea");
	    // 需要加一个状态字段DataDictionary
	    String typeId = "BU_DEPARTMENT";
	    if (isArea.equals("Y")) {
		typeId = "AREA_DEPARTMENT";
	    }
	    List<GenericValue> buInfo = delegator.findByAnd("DataDictionary",
		    UtilMisc.toMap("dictionaryTypeId", typeId, "dictionaryCode", partyIdFrom), null, true);
	    GenericValue buGv = EntityUtil.getFirst(buInfo);

	    GenericValue bu = delegator.findOne("DataDictionary",
		    UtilMisc.toMap("dictionaryId", buGv.getString("dictionaryId")), false);
	    if (enabled.equals("Y")) {
		bu.set("dictionaryCode2", "N");
	    } else {
		bu.set("dictionaryCode2", "Y");
	    }

	    toBeStore.add(bu);

	    // dictionaryCode2 扩展字段 作为bu的状态字段吧

	    List<GenericValue> coRelationshipInfo = delegator.findByAnd("CoRelationship",
		    UtilMisc.toMap("partyIdFrom", partyIdFrom), null, true);

	    for (GenericValue gv : coRelationshipInfo) {
		String partyIdTo = gv.getString("partyIdTo");
		GenericValue personUserLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", partyIdTo),
			false);
		personUserLogin.set("enabled", enabled);
		toBeStore.add(personUserLogin);
	    }

	    Debug.log("toBeStore ===" + toBeStore);
	    delegator.storeAll(toBeStore);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    /**
     * 新建Bu 管理登录用户
     */
    public static Map<String, Object> createCrmBuAdminUserLogin(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	String isArea = (String) context.get("isArea");
	List<GenericValue> toBeStore = new ArrayList<GenericValue>();
	Timestamp now = UtilDateTime.nowTimestamp();
	try {

	    String partyIdFrom = (String) context.get("partyIdFrom");
	    String partyId = (String) context.get("partyId");
	    String userLoginId = (String) context.get("mobile");

//	    List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
//		    UtilMisc.toMap("partyIdFrom", partyIdFrom), null, false);

	    if (isArea.equals("N")) {
		List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT", "dictionaryCode", partyIdFrom), null,
			false);
		GenericValue data = EntityUtil.getFirst(dataList);
		data.set("dictionaryCode3", userLoginId);
		toBeStore.add(data);
		// 对应bu下的所有人员. 如果有bu管理权限,则新增bu人员权限
//		for (GenericValue coRelationship : coRelationshipList) {
//		    String partyIdTo = coRelationship.getString("partyIdTo");
//		    // BU管理权限
//		    List<GenericValue> userLoginSecurityGroupList = delegator.findByAnd("UserLoginSecurityGroup",
//			    UtilMisc.toMap("groupId", "4211", "userLoginId", partyIdTo), null, false);
//
//		    if (UtilValidate.isNotEmpty(userLoginSecurityGroupList)) {
//			delegator.removeByAnd("UserLoginSecurityGroup", UtilMisc.toMap("userLoginId", partyIdTo));
//			// 普通人员权限
//			GenericValue userLoginSecurityGroup = delegator.makeValue("UserLoginSecurityGroup",
//				UtilMisc.toMap("userLoginId", partyIdTo));
//			userLoginSecurityGroup.set("groupId", "4210");
//			userLoginSecurityGroup.set("fromDate", now);
//			toBeStore.add(userLoginSecurityGroup);
//		    }
//		    GenericValue personUserLogin = delegator.findOne("UserLogin", false, UtilMisc.toMap("userLoginId", partyIdTo));
//		    personUserLogin.set("superiorId", userLoginId);
//		    toBeStore.add(personUserLogin);
//		}
		// 判断原先是否有大区管理权限
//		List<GenericValue> oldGroupList = delegator.findByAnd("UserLoginSecurityGroup",
//			UtilMisc.toMap("userLoginId", userLoginId, "groupId", "4213"), null, false);
//		String isOk = "N";
//		String oldPartyIdFrom = "";
//		if (UtilValidate.isNotEmpty(oldGroupList)) {
//		    isOk = "Y";
//		    // 大区编码
//		    List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
//			    UtilMisc.toMap("dictionaryTypeId", "AREA_DEPARTMENT"), null, false);
//		    for (GenericValue data : dataList) {
//			if (UtilValidate.isNotEmpty(data.get("dictionaryCode"))) {
//			    List<GenericValue> oldList1 = delegator.findByAnd("CoRelationship", UtilMisc
//				    .toMap("partyIdTo", userLoginId, "partyIdFrom", data.getString("dictionaryCode")),
//				    null, false);
//			    if (UtilValidate.isNotEmpty(oldList1)) {
//				oldPartyIdFrom = data.getString("dictionaryCode");
//			    }
//			}
//		    }
//		}
		// 如果没有账号,则创建账号.
//		GenericValue person = delegator.findOne("Person", false, UtilMisc.toMap("partyId", partyId));
//		if ("CRM".equals(person.getString("isModule"))) {
//		    delegator.removeByAnd("CoRelationship", UtilMisc.toMap("partyIdTo", userLoginId));
//		} else {
//		    person.set("isModule", "CRM");
//		    toBeStore.add(person);
//		    GenericValue personUserLogin = delegator.makeValue("UserLogin",
//			    UtilMisc.toMap("userLoginId", userLoginId));
//		    personUserLogin.set("isModule", "CRM");
//		    // personUserLogin.set("superiorId", ownerUserId);
//		    personUserLogin.set("currentPassword", "$SHA$E$9o47kQ0nGedqrub1Jn1BIoMUWHE");
//		    personUserLogin.set("partyId", partyId);
//		    toBeStore.add(personUserLogin);
//		}

		// 增加bu管理权限
//		delegator.removeByAnd("UserLoginSecurityGroup", UtilMisc.toMap("userLoginId", userLoginId));
		GenericValue userLoginSecurityGroup = delegator.makeValue("UserLoginSecurityGroup",
			UtilMisc.toMap("userLoginId", userLoginId));
		userLoginSecurityGroup.set("groupId", "4211");
		userLoginSecurityGroup.set("fromDate", now);
		toBeStore.add(userLoginSecurityGroup);
//		if (isOk.equals("Y")) {
//		    GenericValue userLoginSecurityGroup1 = delegator.makeValue("UserLoginSecurityGroup",
//			    UtilMisc.toMap("userLoginId", userLoginId));
//		    userLoginSecurityGroup1.set("groupId", "4213");
//		    userLoginSecurityGroup1.set("fromDate", now);
//		    toBeStore.add(userLoginSecurityGroup1);
//		    if (UtilValidate.isNotEmpty(oldPartyIdFrom)) {
//			// 增加关联关系
//			GenericValue currCoRelationship = delegator.makeValue("CoRelationship",
//				UtilMisc.toMap("partyIdFrom", oldPartyIdFrom, "partyIdTo", userLoginId));
//			currCoRelationship.set("statusId", "PARTY_ENABLED");
//			currCoRelationship.set("partyRelationshipTypeId", "COMPANY_EMPLOYEE");
//			currCoRelationship.set("fromDate", now);
//			toBeStore.add(currCoRelationship);
//		    }
//		}
		// 增加关联关系
//		GenericValue currCoRelationship = delegator.makeValue("CoRelationship",
//			UtilMisc.toMap("partyIdFrom", partyIdFrom, "partyIdTo", userLoginId));
//		currCoRelationship.set("statusId", "PARTY_ENABLED");
//		currCoRelationship.set("partyRelationshipTypeId", "COMPANY_EMPLOYEE");
//		currCoRelationship.set("fromDate", now);
//		toBeStore.add(currCoRelationship);
	    } else {
		List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryTypeId", "AREA_DEPARTMENT", "dictionaryCode", partyIdFrom), null,
			false);
		GenericValue data = EntityUtil.getFirst(dataList);
		data.set("dictionaryCode3", userLoginId);
		toBeStore.add(data);
		// 对应大区下的所有人员. 如果有大区管理权限,则新增bu人员权限
//		for (GenericValue coRelationship : coRelationshipList) {
//		    String partyIdTo = coRelationship.getString("partyIdTo");
//		    // 大区管理权限
//		    List<GenericValue> userLoginSecurityGroupList = delegator.findByAnd("UserLoginSecurityGroup",
//			    UtilMisc.toMap("groupId", "4213", "userLoginId", partyIdTo), null, false);
//
//		    if (UtilValidate.isNotEmpty(userLoginSecurityGroupList)) {
//			delegator.removeByAnd("UserLoginSecurityGroup", UtilMisc.toMap("userLoginId", partyIdTo));
//			// 普通人员权限
//			GenericValue userLoginSecurityGroup = delegator.makeValue("UserLoginSecurityGroup",
//				UtilMisc.toMap("userLoginId", partyIdTo));
//			userLoginSecurityGroup.set("groupId", "4210");
//			userLoginSecurityGroup.set("fromDate", now);
//			toBeStore.add(userLoginSecurityGroup);
//		    }
//
//		    GenericValue personUserLogin = delegator.findOne("UserLogin", false, UtilMisc.toMap("userLoginId", partyIdTo));
//		    personUserLogin.set("superiorId", userLoginId);
//		    toBeStore.add(personUserLogin);
//		}
		// 增加大区管理权限
		// 判断原先是否有bu管理权限
//		List<GenericValue> oldGroupList = delegator.findByAnd("UserLoginSecurityGroup",
//			UtilMisc.toMap("userLoginId", userLoginId, "groupId", "4211"), null, false);
//		String isOk = "N";
//		String oldPartyIdFrom = "";
//		if (UtilValidate.isNotEmpty(oldGroupList)) {
//		    isOk = "Y";
//		    // bu编码
//		    List<GenericValue> dataList = delegator.findByAnd("DataDictionary",
//			    UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT"), null, false);
//		    for (GenericValue data : dataList) {
//			if (UtilValidate.isNotEmpty(data.get("dictionaryCode"))) {
//			    List<GenericValue> oldList1 = delegator.findByAnd("CoRelationship", UtilMisc
//				    .toMap("partyIdTo", userLoginId, "partyIdFrom", data.getString("dictionaryCode")),
//				    null, false);
//			    if (UtilValidate.isNotEmpty(oldList1)) {
//				oldPartyIdFrom = data.getString("dictionaryCode");
//			    }
//			}
//		    }
//		}
		// 如果没有账号,则创建账号.
//		GenericValue person = delegator.findOne("Person", false, UtilMisc.toMap("partyId", partyId));
//		if ("CRM".equals(person.getString("isModule"))) {
//		    delegator.removeByAnd("CoRelationship", UtilMisc.toMap("partyIdTo", userLoginId));
//		} else {
//		    person.set("isModule", "CRM");
//		    toBeStore.add(person);
//		    GenericValue personUserLogin = delegator.makeValue("UserLogin",
//			    UtilMisc.toMap("userLoginId", userLoginId));
//		    personUserLogin.set("isModule", "CRM");
//		    // personUserLogin.set("superiorId", ownerUserId);
//		    personUserLogin.set("currentPassword", "$SHA$E$9o47kQ0nGedqrub1Jn1BIoMUWHE");
//		    personUserLogin.set("partyId", partyId);
//		    toBeStore.add(personUserLogin);
//		}
//
//		// 增加大区管理权限
//		delegator.removeByAnd("UserLoginSecurityGroup", UtilMisc.toMap("userLoginId", userLoginId));
		GenericValue userLoginSecurityGroup = delegator.makeValue("UserLoginSecurityGroup",
			UtilMisc.toMap("userLoginId", userLoginId));
		userLoginSecurityGroup.set("groupId", "4213");
		userLoginSecurityGroup.set("fromDate", now);
		toBeStore.add(userLoginSecurityGroup);
//		if (isOk.equals("Y")) {
//		    GenericValue userLoginSecurityGroup1 = delegator.makeValue("UserLoginSecurityGroup",
//			    UtilMisc.toMap("userLoginId", userLoginId));
//		    userLoginSecurityGroup1.set("groupId", "4211");
//		    userLoginSecurityGroup1.set("fromDate", now);
//		    toBeStore.add(userLoginSecurityGroup1);
//		    if (UtilValidate.isNotEmpty(oldPartyIdFrom)) {
//			// 增加关联关系
//			GenericValue currCoRelationship = delegator.makeValue("CoRelationship",
//				UtilMisc.toMap("partyIdFrom", oldPartyIdFrom, "partyIdTo", userLoginId));
//			currCoRelationship.set("statusId", "PARTY_ENABLED");
//			currCoRelationship.set("partyRelationshipTypeId", "COMPANY_EMPLOYEE");
//			currCoRelationship.set("fromDate", now);
//			toBeStore.add(currCoRelationship);
//		    }
//		}
//
//		// 增加关联关系
//		GenericValue currCoRelationship = delegator.makeValue("CoRelationship",
//			UtilMisc.toMap("partyIdFrom", partyIdFrom, "partyIdTo", userLoginId));
//		currCoRelationship.set("statusId", "PARTY_ENABLED");
//		currCoRelationship.set("partyRelationshipTypeId", "COMPANY_EMPLOYEE");
//		currCoRelationship.set("fromDate", now);
//		toBeStore.add(currCoRelationship);
		// 增加子表的关联关系
	    }

//	    Debug.log("toBeStore ===" + toBeStore);
	    delegator.storeAll(toBeStore);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    /**
     * 新建登录用户
     */
    public static Map<String, Object> createCrmUserLogin(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	Map<String, Object> result = new HashMap<>();
	LocalDispatcher dispatcher = dctx.getDispatcher();
	List toBeStore = new ArrayList();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	Timestamp now = UtilDateTime.nowTimestamp();
	try {

	    String partyId = (String) context.get("partyId");
	    String userLoginId = (String) context.get("mobile");
	    String buCode = (String) context.get("buCode");
	    GenericValue person = delegator.findOne("Person", false, UtilMisc.toMap("partyId", partyId));
	    person.set("isModule", "CRM");
	    toBeStore.add(person);

	    GenericValue personUserLogin = delegator.makeValue("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
	    personUserLogin.set("isModule", "CRM");
	    personUserLogin.set("superiorId", ownerUserId);
	    personUserLogin.set("currentPassword", "$SHA$E$9o47kQ0nGedqrub1Jn1BIoMUWHE");
	    personUserLogin.set("partyId", partyId);
	    toBeStore.add(personUserLogin);
	    
	    List<GenericValue> oldShipList = delegator.findByAnd("CoRelationship", UtilMisc.toMap("partyIdTo", userLoginId),
		    null, false);
	    if(UtilValidate.isNotEmpty(oldShipList)) {
		delegator.removeAll(oldShipList);
	    }
	    
	    List coRelationshipInfo = delegator.findByAnd("CoRelationship", UtilMisc.toMap("partyIdTo", ownerUserId),
		    null, true);
	    GenericValue coRelationship = EntityUtil.getFirst(coRelationshipInfo);
	    String partyIdFrom = "";
	    if(UtilValidate.isNotEmpty(coRelationship)) {
		partyIdFrom = coRelationship.getString("partyIdFrom");
	    }
	    if(UtilValidate.isNotEmpty(buCode)) {
		partyIdFrom = buCode;
	    }
	    GenericValue currCoRelationship = delegator.makeValue("CoRelationship",
		    UtilMisc.toMap("partyIdFrom", partyIdFrom, "partyIdTo", userLoginId));
	    currCoRelationship.set("statusId", "PARTY_ENABLED");
	    currCoRelationship.set("partyRelationshipTypeId", "COMPANY_EMPLOYEE");
	    currCoRelationship.set("fromDate", now);
	    toBeStore.add(currCoRelationship);

	    GenericValue userLoginSecurityGroup = delegator.makeValue("UserLoginSecurityGroup",
		    UtilMisc.toMap("userLoginId", userLoginId));
	    userLoginSecurityGroup.set("groupId", "4210");
	    userLoginSecurityGroup.set("fromDate", now);

	    if ("managebu".equals(partyIdFrom)) {
		userLoginSecurityGroup.set("groupId", "4211");
		Map service_context = new HashMap<>();
		service_context.put("userLogin", userLogin);
		service_context.put("mobile", userLoginId);
		dispatcher.runAsync("createAllBuSceneByUserLoginId", service_context);

	    }
	    toBeStore.add(userLoginSecurityGroup);

	    Debug.log("toBeStore ===" + toBeStore);
	    delegator.storeAll(toBeStore);

	    Map service_context = new HashMap();

	    service_context.put("userLogin", userLogin);
	    service_context.put("mobile", userLoginId);

	    dispatcher.runAsync("checkSingleCrmUserLoginScene", service_context);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    /**
     * 重置登录用户密码
     */
    public static Map<String, Object> resetCrmUserLoginPassword(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();

	// GenericValue userLogin = (GenericValue)context.get("userLogin");
	// String ownerUserId=userLogin.getString("userLoginId");
	// Timestamp now =UtilDateTime.nowTimestamp();
	try {

	    String userLoginId = (String) context.get("mobile");

	    GenericValue personUserLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId),
		    false);

	    personUserLogin.set("currentPassword", "$SHA$E$9o47kQ0nGedqrub1Jn1BIoMUWHE");

	    Debug.log("personUserLogin ===" + personUserLogin);
	    delegator.store(personUserLogin);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    /**
     * 禁用或启用登录用户
     */
    public static Map<String, Object> updateCrmUserLoginEnabled(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();

	GenericValue userLogin = (GenericValue) context.get("userLogin");
	// String ownerUserId=userLogin.getString("userLoginId");
	Timestamp now = UtilDateTime.nowTimestamp();
	try {

	    String enabled = (String) context.get("enabled");
	    String userLoginId = (String) context.get("mobile");

	    GenericValue personUserLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId),
		    false);

	    if ("Y".equals(enabled)) {
		personUserLogin.set("enabled", enabled);
		personUserLogin.set("disabledDateTime", null);
	    } else {
		personUserLogin.set("enabled", "N");
		personUserLogin.set("disabledDateTime", now);

	    }
	    delegator.store(personUserLogin);

	    Debug.log("personUserLogin ===" + personUserLogin);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    /**
     * 根据用户本人CrmScene数据，查看是否生成下拉数据 如没有则生成下拉数据
     */

    public static Map<String, Object> checkAllCrmUserLoginScene(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	LocalDispatcher dispatcher = dctx.getDispatcher();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	try {

	    List<GenericValue> crmUserLoginList = delegator.findByAnd("UserLogin", UtilMisc.toMap("isModule", "CRM"),
		    null, true);

	    for (GenericValue crmUserLogin : crmUserLoginList) {

		// String mobile = crmUserLogin.getString("userLoginId");

		// List<GenericValue> crmSceneList =
		// delegator.findByAnd("CrmScene",UtilMisc.toMap("sceneId",mobile+"Owner"),null,
		// false);

		// if(UtilValidate.isEmpty(crmSceneList)) {
		Map<String, Object> service_context = new HashMap<>();
		service_context.put("userLogin", userLogin);
		service_context.put("mobile", crmUserLogin.getString("userLoginId"));
		dispatcher.runSync("checkSingleCrmUserLoginScene", service_context);
		// }

	    }

	    Debug.log("crmUserLoginList ===" + crmUserLoginList);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    /**
     * 根据用户手机号，生成下拉数据
     */
    public static Map<String, Object> checkSingleCrmUserLoginScene(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();

	try {

	    String userLoginId = (String) context.get("mobile");
	    Debug.log("userLoginId ===" + userLoginId);
	    GenericValue personUserLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId),
		    false);

//			personUserLogin.set("currentPassword", "$SHA$E$9o47kQ0nGedqrub1Jn1BIoMUWHE");

	    Debug.log("personUserLogin ===" + personUserLogin);
//			delegator.store(personUserLogin);

//			List<GenericValue> crmSceneList = delegator.findByAnd("CrmScene",UtilMisc.toMap("userId",userLoginId),null, false);
//			
//			if(UtilValidate.isNotEmpty(crmSceneList)) {
//				return result;
//			}

	    List toBeStore = new ArrayList();

	    GenericValue cmsCustomer_Owner = delegator.makeValue("CrmScene",
		    UtilMisc.toMap("sceneId", userLoginId + "Owner"));
	    cmsCustomer_Owner.set("isDefault", "0");
	    cmsCustomer_Owner.set("isHide", "0");
	    cmsCustomer_Owner.set("name", "本人");

	    cmsCustomer_Owner.set("sceneData", makeSceneDataListJsonString(userLoginId));
	    cmsCustomer_Owner.set("sceneSort", new Long(0));
	    cmsCustomer_Owner.set("type", "CmsCustomer");
	    cmsCustomer_Owner.set("userId", userLoginId);
	    toBeStore.add(cmsCustomer_Owner);

	    GenericValue cmsCustomer_Team = delegator.makeValue("CrmScene",
		    UtilMisc.toMap("sceneId", userLoginId + "Team"));
	    cmsCustomer_Team.set("isDefault", "0");
	    cmsCustomer_Team.set("isHide", "0");
	    cmsCustomer_Team.set("name", "本BU");

	    cmsCustomer_Team.set("sceneData",
		    makeSceneDataListJsonString(makeUserLoginIdBySuperiorId(delegator, userLoginId)));
	    cmsCustomer_Team.set("sceneSort", new Long(2));
	    cmsCustomer_Team.set("type", "CmsCustomer");
	    cmsCustomer_Team.set("userId", userLoginId);
	    toBeStore.add(cmsCustomer_Team);

	    GenericValue crmBusiness_NessOwner = delegator.makeValue("CrmScene",
		    UtilMisc.toMap("sceneId", userLoginId + "NessOwner"));
	    crmBusiness_NessOwner.set("isDefault", "0");
	    crmBusiness_NessOwner.set("isHide", "0");
	    crmBusiness_NessOwner.set("name", "本人");

	    crmBusiness_NessOwner.set("sceneData", makeSceneDataListJsonString(userLoginId));
	    crmBusiness_NessOwner.set("sceneSort", new Long(0));
	    crmBusiness_NessOwner.set("type", "CrmBusiness");
	    crmBusiness_NessOwner.set("userId", userLoginId);
	    toBeStore.add(crmBusiness_NessOwner);

	    GenericValue crmBusiness_NessTeam = delegator.makeValue("CrmScene",
		    UtilMisc.toMap("sceneId", userLoginId + "NessTeam"));
	    crmBusiness_NessTeam.set("isDefault", "0");
	    crmBusiness_NessTeam.set("isHide", "0");
	    crmBusiness_NessTeam.set("name", "本BU");

	    crmBusiness_NessTeam.set("sceneData",
		    makeSceneDataListJsonString(makeUserLoginIdBySuperiorId(delegator, userLoginId)));
	    crmBusiness_NessTeam.set("sceneSort", new Long(2));
	    crmBusiness_NessTeam.set("type", "CrmBusiness");
	    crmBusiness_NessTeam.set("userId", userLoginId);
	    toBeStore.add(crmBusiness_NessTeam);

	    if (UtilValidate.isNotEmpty(personUserLogin.getString("superiorId"))) {
		String superiorId = personUserLogin.getString("superiorId");
		String partyId = personUserLogin.getString("partyId");
		GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", partyId), false);
		String name = person.getString("name");

		GenericValue crmScene_Subor = delegator.makeValue("CrmScene",
			UtilMisc.toMap("sceneId", userLoginId + "Subor"));
		crmScene_Subor.set("isDefault", "0");
		crmScene_Subor.set("isHide", "0");
		crmScene_Subor.set("name", name);

		crmScene_Subor.set("sceneData", makeSceneDataListJsonString(userLoginId));
		crmScene_Subor.set("sceneSort", new Long(6));
		crmScene_Subor.set("type", "CmsCustomer");
		crmScene_Subor.set("userId", superiorId);
		toBeStore.add(crmScene_Subor);

		GenericValue crmScene_NessSubor = delegator.makeValue("CrmScene",
			UtilMisc.toMap("sceneId", userLoginId + "NessSubor"));
		crmScene_NessSubor.set("isDefault", "0");
		crmScene_NessSubor.set("isHide", "0");
		crmScene_NessSubor.set("name", name);

		crmScene_NessSubor.set("sceneData", makeSceneDataListJsonString(userLoginId));
		crmScene_NessSubor.set("sceneSort", new Long(6));
		crmScene_NessSubor.set("type", "CrmBusiness");
		crmScene_NessSubor.set("userId", superiorId);
		toBeStore.add(crmScene_NessSubor);

	    }

	    delegator.storeAll(toBeStore);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    /**
     * 根据用户手机号生成全部bu的下拉数据
     */
    public static Map<String, Object> createAllBuSceneByUserLoginId(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();

	try {

	    String mobile = (String) context.get("mobile");
	    Debug.log("mobile ===" + mobile);

	    List<GenericValue> ulsgList = delegator.findByAnd("UserLoginSecurityGroup",
		    UtilMisc.toMap("groupId", "4211"), null, false);

	    Debug.log("ulsgList ===" + ulsgList);

	    List toBeStore = new ArrayList();

	    for (GenericValue ulsg : ulsgList) {

		String ulsgUserLoginId = ulsg.getString("userLoginId");
		List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship", UtilMisc.toMap("statusId",
			"PARTY_ENABLED", "partyRelationshipTypeId", "COMPANY_EMPLOYEE", "partyIdTo", ulsgUserLoginId),
			null, false);
		Debug.log("coRelationshipList ===" + coRelationshipList);

		if (UtilValidate.isEmpty(coRelationshipList)) {
		    continue;
		}
		GenericValue coRelationship = EntityUtil.getFirst(coRelationshipList);
		String buId = coRelationship.getString("partyIdFrom");

		List<GenericValue> dataDictionaryList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryCode", buId, "dictionaryTypeId", "BU_DEPARTMENT"), null, false);

		if (UtilValidate.isEmpty(dataDictionaryList)) {
		    continue;
		}
		Debug.log("dataDictionaryList ===" + dataDictionaryList);
		GenericValue dataDictionary = EntityUtil.getFirst(dataDictionaryList);
		String buName = dataDictionary.getString("description");

		GenericValue cmsCustomer_Team = delegator.makeValue("CrmScene",
			UtilMisc.toMap("sceneId", mobile + buId + "Team"));
		cmsCustomer_Team.set("isDefault", "0");
		cmsCustomer_Team.set("isHide", "0");
		cmsCustomer_Team.set("name", buName);

		cmsCustomer_Team.set("sceneData",
			makeSceneDataListJsonString(makeUserLoginIdBySuperiorId(delegator, ulsgUserLoginId)));
		cmsCustomer_Team.set("sceneSort", new Long(6));
		cmsCustomer_Team.set("type", "CmsCustomer");
		cmsCustomer_Team.set("userId", mobile);
		toBeStore.add(cmsCustomer_Team);

		Debug.log("mobile+buId+Team ===" + mobile + buId + "Team");

		GenericValue crmBusiness_NessTeam = delegator.makeValue("CrmScene",
			UtilMisc.toMap("sceneId", mobile + buId + "NessTeam"));
		crmBusiness_NessTeam.set("isDefault", "0");
		crmBusiness_NessTeam.set("isHide", "0");
		crmBusiness_NessTeam.set("name", buName);

		crmBusiness_NessTeam.set("sceneData",
			makeSceneDataListJsonString(makeUserLoginIdBySuperiorId(delegator, ulsgUserLoginId)));
		crmBusiness_NessTeam.set("sceneSort", new Long(6));
		crmBusiness_NessTeam.set("type", "CrmBusiness");
		crmBusiness_NessTeam.set("userId", mobile);
		toBeStore.add(crmBusiness_NessTeam);

		Debug.log("mobile+buId+NessTeam ===" + mobile + buId + "NessTeam");
	    }

	    Debug.log("toBeStore ===" + toBeStore);
	    delegator.storeAll(toBeStore);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    private static String makeSceneDataListJsonString(String value) {
	List sceneData_list = new ArrayList();
	Map sceneData_map = new HashMap();
	sceneData_map.put("name", "ownerUserId_dictText");
	sceneData_map.put("type", "10");
	sceneData_map.put("value", value);
	sceneData_map.put("formType", "list_multi");
	sceneData_map.put("dictUrl", "listUserLoginBySuperiorId");
	sceneData_map.put("name", "ownerUserId_dictText");
	sceneData_list.add(sceneData_map);
	Gson gson = new Gson();
	String sceneData = gson.toJson(sceneData_list);

	return sceneData;

    }

    private static String makeUserLoginIdBySuperiorId(Delegator delegator, String superiorId)
	    throws GenericEntityException {
	String result = superiorId;
	List<GenericValue> crmUserLoginList = delegator.findByAnd("UserLogin", UtilMisc.toMap("superiorId", superiorId),
		null, true);

	// List list= new ArrayList();
	for (GenericValue crmUserLogin : crmUserLoginList) {

	    String mobile = crmUserLogin.getString("userLoginId");
	    // list.add(mobile);
	    result = result + "," + mobile;
	}
	// result =StringUtils.join(list,",");
	return result;
    }

    /**
     * 根据bu管理员的本bu 的CrmScene数据，查看是否生成足够下属的搜索条件 如没有则生成下拉数据
     */

    public static Map<String, Object> checkManageBuScene(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	LocalDispatcher dispatcher = dctx.getDispatcher();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	try {

	    List toBeStore = new ArrayList();
	    List<GenericValue> crmUserLoginList = delegator.findByAnd("UserLogin", UtilMisc.toMap("isModule", "CRM"),
		    null, true);
	    for (GenericValue crmUserLogin : crmUserLoginList) {
		String mobile = crmUserLogin.getString("userLoginId");

		String suborUserLoginListString = makeUserLoginIdBySuperiorId(delegator, mobile);
		Debug.log("suborUserLoginList = " + suborUserLoginListString);
		if (!mobile.equals(suborUserLoginListString)) {
		    GenericValue oldCustomer_Team = delegator.findOne("CrmScene",
			    UtilMisc.toMap("sceneId", mobile + "Team"), false);
		    if (UtilValidate.isNotEmpty(oldCustomer_Team)) {
			String sceneDataString = (String) oldCustomer_Team.get("sceneData");
			Debug.log("sceneDataString = " + sceneDataString);
			Gson gson = new Gson();
			List<Map> sceneDataList = gson.fromJson(sceneDataString, new TypeToken<List<Map>>() {
			}.getType());
			if (UtilValidate.isNotEmpty(sceneDataList)) {
			    Map sceneData = sceneDataList.get(0);
			    String value = (String) sceneData.get("value");
			    Debug.log("value = " + value);
			    if (!suborUserLoginListString.equals(value)) {

				GenericValue crmCustomer_Team = delegator.makeValue("CrmScene",
					UtilMisc.toMap("sceneId", mobile + "Team"));
				crmCustomer_Team.set("isDefault", "0");
				crmCustomer_Team.set("isHide", "0");
				crmCustomer_Team.set("name", "本BU");

				crmCustomer_Team.set("sceneData",
					makeSceneDataListJsonString(suborUserLoginListString));
				crmCustomer_Team.set("sceneSort", new Long(2));
				crmCustomer_Team.set("type", "CmsCustomer");
				crmCustomer_Team.set("userId", mobile);
				toBeStore.add(crmCustomer_Team);
				Debug.log("crmCustomer_Team = " + crmCustomer_Team);
				GenericValue crmBusiness_NessTeam = delegator.makeValue("CrmScene",
					UtilMisc.toMap("sceneId", mobile + "NessTeam"));
				crmBusiness_NessTeam.set("isDefault", "0");
				crmBusiness_NessTeam.set("isHide", "0");
				crmBusiness_NessTeam.set("name", "本BU");

				crmBusiness_NessTeam.set("sceneData",
					makeSceneDataListJsonString(makeUserLoginIdBySuperiorId(delegator, mobile)));
				crmBusiness_NessTeam.set("sceneSort", new Long(2));
				crmBusiness_NessTeam.set("type", "CrmBusiness");
				crmBusiness_NessTeam.set("userId", mobile);
				toBeStore.add(crmBusiness_NessTeam);
				Debug.log("crmBusiness_NessTeam = " + crmBusiness_NessTeam);

			    }
			}

		    }
		}

	    }

	    Debug.log("crmUserLoginList ===" + crmUserLoginList);
	    delegator.storeAll(toBeStore);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    // SELECT user_id ,COUNT(*) AS count FROM Crm_Scene GROUP BY user_id HAVING
    // count(user_id) >2
    public static void main(String[] args) {

	List list = new ArrayList();

	list.add("22222");
	list.add("4444");
	list.add("55555");
	list.add("77777");

	String result = StringUtils.join(list, ",");
	System.out.println(result);
    }
    
    
    public static Map<String, Object> listWvVisitLogReport(DispatchContext dctx, Map<String, ? extends Object> context) {
    	Map<String, Object> result = ServiceUtil.returnSuccess();
    	Delegator delegator = dctx.getDelegator();
    	GenericValue userLogin = (GenericValue) context.get("userLogin");
    	Debug.log("listWvVisitLogReport == start");
//    	String ownerUserId = userLogin.getString("userLoginId");
    	Timestamp fromDate = (Timestamp) context.get("fromDate"); // 开始时间
    	Timestamp thruDate = (Timestamp) context.get("thruDate"); // 结束时间
    	
    	List<Map> dataList = new ArrayList();

//    	String onlyBu = (String) context.get("onlyBu");
//    	List<String> baseIdList = new ArrayList();
    	try {
    		
    		
    		EntityCondition mainCond = null;
    	    List<EntityCondition> andExprs = FastList.newInstance();
    	    if(UtilValidate.isNotEmpty(fromDate)) {
    	    	andExprs.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
        	    	
    	    }
    	    if(UtilValidate.isNotEmpty(thruDate)) {
    	        andExprs.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
    	    }
    	    
    	    
    	    andExprs.add(EntityCondition.makeCondition("createUserId", EntityOperator.NOT_EQUAL, "admin"));
    	    if (andExprs.size() > 0) {
    		mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
    	    }

    	    // 按仓库统计 销售情况
    	   // List salesDataListByWarehouse = new ArrayList();

    	    // 销售预警
    	   // List cautionSalesDataListByWarehouse = new ArrayList();

    	    List orderBy = UtilMisc.toList("createTime");
    		 List<GenericValue> entityList = delegator.findList("WvVisitLog", mainCond, null, orderBy, null, true);

    		//List<GenericValue> entityList =delegator.findAll("WvVisitLog", true);
    		
    		
    		 Map dataCollection =wvVisitLogDataCollection( delegator,entityList);
 		    
    		 dataList = new ArrayList<Map>(dataCollection.values());
  		   
 		    // 按照单量进行排序
 		    Collections.sort(dataList, new Comparator<Map>() {
 			@Override
 			public int compare(Map obj1, Map obj2) {
 			    int i = ((Long) obj2.get("clickQty")).compareTo((Long) obj1.get("clickQty"));
 			    return i;// 这里返回的只是一个int类型的数据
 			}
 		    });
    	    Map<String, Object> workMap = FastMap.newInstance();

    	    workMap.put("dataList", dataList);

    	    result.put("workMap", workMap);
    	    Debug.log("listWvVisitLogReport == end");
    	} catch (Exception e) {
    	    Debug.logError(e.getMessage(), module);
    	}
    	return result;
        }
    
    private static Map wvVisitLogDataCollection(Delegator delegator,List<GenericValue> entityList) throws GenericEntityException {
		Map dataCollection = new HashMap();
	    for (GenericValue entity : entityList) {
	    	dataCollection =addWvVisitLogDataCollection( delegator,dataCollection, entity);
//		    Debug.log("dataCollection = " + dataCollection);
	    }
	    
	    return  dataCollection ;
	}
    
    
    private static Map addWvVisitLogDataCollection(Delegator delegator, Map dataCollection, Map newData)
		    throws GenericEntityException {
		Map result = dataCollection;
		String createUserId = (String) newData.get("createUserId");
//		String customerName = (String) newData.get("customerName");


		Map data = new HashMap();
		if (UtilValidate.isEmpty(dataCollection.get(createUserId))) {

			String createUserId_dictText =getPersonName(delegator, createUserId);
			data.put("createUserId", createUserId);
			data.put("createUserId_dictText", createUserId_dictText);
			data.put("clickQty", 1L);
			Map item =new HashMap();
			item.putAll(newData);
			item.put("createUserId_dictText", createUserId_dictText);
			List itemList =UtilMisc.toList(item);
			data.put("itemList", itemList);
		    
		} else {

		    Map oldData = (Map) dataCollection.get(createUserId);
		    data.putAll(oldData);
		    Long addQty = 1L+(Long) oldData.get("clickQty");
		    data.put("clickQty", addQty);
		    
		    
		    List itemList =(List) oldData.get("itemList");
		    Map item =new HashMap();
			item.putAll(newData);
			String createUserId_dictText =getPersonName(delegator, createUserId);
			item.put("createUserId_dictText", createUserId_dictText);
		    itemList.add(item);
		    
		    Collections.sort(itemList, new Comparator<Map>() {
	 			@Override
	 			public int compare(Map obj1, Map obj2) {
	 			    int i = ((Timestamp) obj2.get("createTime")).compareTo((Timestamp) obj1.get("createTime"));
	 			    return i;// 这里返回的只是一个int类型的数据
	 			}
	 		    });
			data.put("itemList", itemList);
		}
		
		result.put(createUserId, data);
		return result;

	    }
 // crm 同名方法
    private static String getPersonName(Delegator delegator, String userLoginId) throws GenericEntityException {
	String result = "";

	GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId), true);

	if (UtilValidate.isNotEmpty(userLogin)) {
	    GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", userLogin.getString("partyId")),
		    true);
	    if (UtilValidate.isNotEmpty(person)) {
		String personName = person.getString("name");
		result = personName;
	    }
	}
	return result;
    }
	

}
